#include <iterator>
#include "MarkupSTL.h"
#include "global.h"
#include "Game.h"
#include "RedisClient.h"
#include "Logic.h"
#include "json.h"
#include "util.h"
#include "globalExtern.h"
#include "Host.h"
#include "CClient.h"
#include "NodeServer.h"
#include "Host.h"
#include <atomic>
#include <thread>
#include "log.h"
#include "json.h"
#include "util.h"
#include "streamdata.h"
#include <functional>
#include "context.h"
#include "def.h"
#include "minutelisten.h"
#include "agencymgr.h"


CGameServer::CGameServer()
{
}

CGameServer::~CGameServer()
{
}

bool CGameServer::InitGame()
{	
	Ctx.host = m_pHost;

	if (!AgencyMgr::Instance()->Init(TGlobal::_str_param))
	{
		log_error("agency Init failed");
		return false;
	}

	if (!Ctx.msg_router.Init(TGlobal::_param1, TGlobal::_str_param))
	{
		log_error("Ctx.msg_router Init failed");
		return false;
	}

	Ctx.timer_event_activator = CActiveEvent::Attach(CCReactor::Instance());
	if (nullptr == Ctx.timer_event_activator)
	{
		log_error("create CActiveEvent fail");
		return -1;
	}
	// 添加定时任务, 主线程
	Ctx.timer_event_activator->SetSignalHandle([this](std::int64_t event){
		TimerEvent u(event);
		this->StartTimerMillisecond(u.stu.timer_id, u.stu.ms, false);
	});

	// 执行 分钟任务
    Ctx.msg_router.BindTimer(TIMER_MINITE, [](int timer_id)->int{
		MinuteListen::Instance()->OnTick();
		return 0;
    });

	StartTimerMillisecond(TimerID::TIMER_MINITE, 60*1000, true);
	
	return true;
}

int CGameServer::OnBYTimeOut(int Timerid)
{
    Ctx.msg_router.ReceiveTimerData(Timerid);
	return 0;
}

int CGameServer::ProcessPacket(SocketHandler* pHandler, NETInputPacket* inputPkg)
{
	log_debug("cmd=0x%x,uuid:%d", inputPkg->GetCmdType(), inputPkg->GetSeq());

	int cmd = inputPkg->GetCmdType();
	try
	{
		MsgData msg_data;
		msg_data.svtype = pHandler->getType();
		msg_data.svid = pHandler->getId();
		msg_data.from_client = (inputPkg->GetSrcType() == SERVER_TYPE_GAME_PLAYER);
		msg_data.cmd = cmd;
		msg_data.uuid = inputPkg->GetSeq();
		inputPkg->getPbData(msg_data.data);

		Ctx.msg_router.ReceiveMsgData(std::move(msg_data));
	}
	catch(const std::exception& e)
	{
		log_error("cmd=0x%x,error:%s", inputPkg->GetCmdType(), e.what());
		return 0;
	}
	catch(...)
	{
		log_error("cmd=0x%x, unknown exception", inputPkg->GetCmdType());
		return 0;
	}
	
	return 0;
}

int CGameServer::ProcEventBackConn(int ev_id, SpiderEvent* pEvent)
{
	return 0;
}







